<template>
  <div class="auth-container">
    <div class="auth-wrapper">
      <!-- 左侧品牌区域 -->
      <div class="brand-section">
        <div class="brand-content">
          <img src="/xiaomilogo.png" alt="小米有品" class="brand-logo" />
          <h1 class="brand-title">小米有品</h1>
          <p class="brand-subtitle">精品生活，品质之选</p>
        </div>
      </div>

      <!-- 右侧表单区域 -->
      <div class="form-section">
        <div class="form-container">
          <div class="form-header">
            <h2>欢迎来到小米有品</h2>
            <p>请选择登录或注册</p>
          </div>

          <!-- Tab切换 -->
          <el-tabs v-model="activeTab" class="auth-tabs">
            <!-- 登录Tab -->
            <el-tab-pane label="登录" name="login">
              <el-form
                ref="loginFormRef"
                :model="loginForm"
                :rules="loginRules"
                class="auth-form"
                @submit.prevent="handleLogin"
              >
                <el-form-item prop="username">
                  <el-input
                    v-model="loginForm.username"
                    placeholder="请输入用户名/手机号/邮箱"
                    size="large"
                    prefix-icon="User"
                  />
                </el-form-item>

                <el-form-item prop="password">
                  <el-input
                    v-model="loginForm.password"
                    type="password"
                    placeholder="请输入密码"
                    size="large"
                    prefix-icon="Lock"
                    show-password
                  />
                </el-form-item>

                <div class="form-options">
                  <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
                </div>

                <el-button
                  type="primary"
                  size="large"
                  class="submit-btn"
                  :loading="loginLoading"
                  @click="handleLogin"
                >
                  登录
                </el-button>
              </el-form>
            </el-tab-pane>

            <!-- 注册Tab -->
            <el-tab-pane label="注册" name="register">
              <el-form
                ref="registerFormRef"
                :model="registerForm"
                :rules="registerRules"
                class="auth-form"
                @submit.prevent="handleRegister"
              >
                <el-form-item prop="phone">
                  <el-input
                    v-model="registerForm.phone"
                    placeholder="请输入手机号"
                    size="large"
                    prefix-icon="Phone"
                  />
                </el-form-item>

                <el-form-item prop="email">
                  <el-input
                    v-model="registerForm.email"
                    placeholder="请输入邮箱"
                    size="large"
                    prefix-icon="Message"
                  />
                </el-form-item>

                <el-form-item prop="password">
                  <el-input
                    v-model="registerForm.password"
                    type="password"
                    placeholder="请输入密码"
                    size="large"
                    prefix-icon="Lock"
                    show-password
                  />
                </el-form-item>

                <el-form-item prop="confirmPassword">
                  <el-input
                    v-model="registerForm.confirmPassword"
                    type="password"
                    placeholder="请确认密码"
                    size="large"
                    prefix-icon="Lock"
                    show-password
                  />
                </el-form-item>



                <el-form-item prop="agreement">
                  <el-checkbox v-model="registerForm.agreement">
                    我已阅读并同意
                    <a href="#" class="agreement-link">《用户协议》</a>
                    和
                    <a href="#" class="agreement-link">《隐私政策》</a>
                  </el-checkbox>
                </el-form-item>

                <el-button
                  type="primary"
                  size="large"
                  class="submit-btn"
                  :loading="registerLoading"
                  @click="handleRegister"
                >
                  注册
                </el-button>
              </el-form>
            </el-tab-pane>
          </el-tabs>

        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { userApi, type LoginRequest, type RegisterRequest } from '@/api/user'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

// 当前激活的Tab
const activeTab = ref('login')

// 加载状态
const loginLoading = ref(false)
const registerLoading = ref(false)

// 表单引用
const loginFormRef = ref<FormInstance>()
const registerFormRef = ref<FormInstance>()

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: '',
  remember: false
})

// 注册表单数据
const registerForm = reactive({
  phone: '',
  email: '',
  password: '',
  confirmPassword: '',
  agreement: false
})



// 登录表单验证规则
const loginRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名、手机号或邮箱', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入用户名、手机号或邮箱'))
          return
        }
        // 检查是否为邮箱格式
        const emailPattern = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/
        // 检查是否为手机号格式
        const phonePattern = /^1[3-9]\d{9}$/
        // 检查是否为用户名格式（3-50位字母数字）
        const usernamePattern = /^[a-zA-Z0-9]{3,50}$/
        
        if (emailPattern.test(value) || phonePattern.test(value) || usernamePattern.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的用户名、手机号或邮箱格式'))
        }
      },
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ]
}

// 注册表单验证规则
const registerRules: FormRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  agreement: [
    { required: true, message: '请同意用户协议', trigger: 'change' }
  ]
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    await loginFormRef.value.validate()
    loginLoading.value = true

    // 构建登录请求数据
    const loginData: LoginRequest = {
      password: loginForm.password
    }

    // 根据输入类型设置对应字段
    const account = loginForm.username
    if (account && account.includes('@')) {
      loginData.email = account
    } else if (account && /^1[3-9]\d{9}$/.test(account)) {
      loginData.phone = account
    } else if (account) {
      loginData.username = account
    }

    // 调用登录API
    const response = await userApi.login(loginData)
    
    if (response.code === 200) {
      // 保存用户信息和token
      try {
        // 使用 userStore 的方法来保存数据
        userStore.setToken(response.data.token)
        userStore.setUser(response.data.userInfo)
      } catch (storeError) {
        console.error('保存用户信息时出错:', storeError)
        throw storeError
      }
      
      ElMessage.success('登录成功！')
      
      // 使用强制刷新页面的方式确保用户状态正确显示
      setTimeout(() => {
        window.location.href = '/'
      }, 1000)
    } else {
      ElMessage.error(response.message || '登录失败')
    }
  } catch (error: any) {
    console.error('登录失败:', error)
    console.error('错误详情:', error.response)
    ElMessage.error(error.response?.data?.message || error.message || '登录失败，请检查账号和密码')
  } finally {
    loginLoading.value = false
  }
}

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return

  try {
    await registerFormRef.value.validate()
    registerLoading.value = true

    // 构建注册请求数据
    const registerData: RegisterRequest = {
      password: registerForm.password
    }

    // 设置手机号或邮箱
    if (registerForm.phone) {
      registerData.phone = registerForm.phone
    }
    if (registerForm.email) {
      registerData.email = registerForm.email
    }

    // 调用注册API
    const response = await userApi.register(registerData)
    
    if (response.code === 200) {
      ElMessage.success('注册成功！请登录')
      
      // 切换到登录tab
      activeTab.value = 'login'
      
      // 清空注册表单
      Object.assign(registerForm, {
        phone: '',
        email: '',
        password: '',
        confirmPassword: '',
        agreement: false
      })
      
      // 重置表单验证状态
      registerFormRef.value?.resetFields()
    } else {
      ElMessage.error(response.message || '注册失败')
    }
  } catch (error: any) {
    console.error('注册失败:', error)
    ElMessage.error(error.response?.data?.message || '注册失败，请重试')
  } finally {
    registerLoading.value = false
  }
}


</script>

<style scoped>
.auth-container {
  min-height: 100vh;
  background: white;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.auth-wrapper {
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  width: 100%;
  max-width: 1000px;
  min-height: 600px;
}

/* 左侧品牌区域 */
.brand-section {
  flex: 1;
  background: linear-gradient(135deg, #ff6900 0%, #ff8533 100%);
  color: white;
  padding: 60px 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.brand-content {
  text-align: center;
  max-width: 300px;
}

.brand-logo {
  width: 80px;
  height: 80px;
  margin-bottom: 20px;
  filter: brightness(0) invert(1);
}

.brand-title {
  font-size: 32px;
  font-weight: 700;
  margin-bottom: 10px;
}

.brand-subtitle {
  font-size: 16px;
  opacity: 0.9;
  margin-bottom: 40px;
}

.brand-features {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 14px;
}

.feature-icon {
  font-size: 20px;
}

/* 右侧表单区域 */
.form-section {
  flex: 1;
  padding: 60px 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.form-container {
  width: 100%;
  max-width: 400px;
}

.form-header {
  text-align: center;
  margin-bottom: 30px;
}

.form-header h2 {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.form-header p {
  color: #666;
  font-size: 14px;
}

/* Tab样式 */
.auth-tabs {
  margin-bottom: 20px;
}

:deep(.el-tabs__header) {
  margin-bottom: 30px;
}

:deep(.el-tabs__nav-wrap::after) {
  display: none;
}

:deep(.el-tabs__item) {
  font-size: 16px;
  font-weight: 500;
  color: #666;
  padding: 0 30px;
}

:deep(.el-tabs__item.is-active) {
  color: #ff6900;
}

:deep(.el-tabs__active-bar) {
  background-color: #ff6900;
}

/* 表单样式 */
.auth-form {
  margin-bottom: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 0 0 1px #e0e0e0;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #ff6900;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px rgba(255, 105, 0, 0.2);
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.forgot-link {
  color: #ff6900;
  text-decoration: none;
  font-size: 14px;
}

.forgot-link:hover {
  text-decoration: underline;
}

.submit-btn {
  width: 100%;
  height: 48px;
  background-color: #ff6900;
  border-color: #ff6900;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
}

.submit-btn:hover {
  background-color: #e55a00;
  border-color: #e55a00;
}



.agreement-link {
  color: #ff6900;
  text-decoration: none;
}

.agreement-link:hover {
  text-decoration: underline;
}

/* 第三方登录 */
.third-party-login {
  margin-top: 30px;
}

.divider {
  text-align: center;
  margin-bottom: 20px;
  position: relative;
}

.divider::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 1px;
  background: #e0e0e0;
}

.divider span {
  background: white;
  padding: 0 15px;
  color: #999;
  font-size: 14px;
}

.third-party-buttons {
  display: flex;
  gap: 10px;
}

.third-party-btn {
  flex: 1;
  height: 44px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.third-party-btn.wechat {
  background-color: #07c160;
  border-color: #07c160;
  color: white;
}

.third-party-btn.qq {
  background-color: #1296db;
  border-color: #1296db;
  color: white;
}

.third-party-icon {
  font-size: 18px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .auth-wrapper {
    flex-direction: column;
    max-width: 400px;
  }

  .brand-section {
    padding: 40px 20px;
  }

  .form-section {
    padding: 40px 20px;
  }

  .brand-features {
    flex-direction: row;
    justify-content: space-around;
  }
}
</style>
